import type { FormInstance, UploadFile, UploadUserFile } from "element-plus"
import type { VideoFormData } from "./types"
import { addVideoData, editVideoData, upload } from "@@/apis/video/index"
import { formatDate } from "@@/utils/datetime"
// useForm.ts
import { ref } from "vue"

// 表单相关逻辑
export function useForm(refreshData: () => void) {
  // 默认表单数据
  const getDefaultFormData = (): VideoFormData => ({
    videoName: "",
    actor: "",
    shortDesc: "",
    coverUrl: "",
    category: "",
    series: "",
    resolution: "1080p",
    releaseDate: formatDate(new Date()),
    subtitle: "外挂字幕",
    videoType: "有码",
    actorList: [],
    imageUrl: ""
  })

  const formData = ref<VideoFormData>(getDefaultFormData())
  const formDataRef = ref<FormInstance>()
  const formRules = {
    videoName: [{ required: true, message: "请输入视频名称", trigger: "blur" }],
    actorList: [
      { required: true, message: "请选择或输入演员", trigger: "blur" }
    ]
  }

  const addDialogVisible = ref(false)
  const fileList = ref<UploadUserFile[]>([])
  const isEdit = ref(false)

  // 显示弹窗
  const showDialog = () => {
    addDialogVisible.value = true
  }

  // 重置表单
  const resetData = () => {
    formData.value = getDefaultFormData()
    formDataRef.value?.resetFields()
    fileList.value = []
    isEdit.value = false
  }

  // 关闭弹窗
  const closeDialog = () => {
    addDialogVisible.value = false
    resetData()
  }

  // 表单提交/图片上传
  const submitForm = async (formEl: FormInstance | undefined, type?: string) => {
    // 上传图片
    if (type === "imageUpload") {
      const imageUrl = formData.value.imageUrl
      if (imageUrl) {
        try {
          const res = await upload({ imageUrl }) as { data: { url: string } }
          const list = {
            name: res.data.url,
            url: import.meta.env.VITE_BASE_URL + res.data.url
          }
          fileList.value = [list]
        } catch (error: any) {
          const mes = error.message || "图片上传失败"
          ElMessage.error(mes)
        }
      }
      return
    }
    // 提交表单
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        try {
          formData.value.actor = formData.value.actorList.join("、")
          if (isEdit.value) {
            await editVideoData(formData.value)
          } else {
            await addVideoData(formData.value)
          }
          ElMessage.success("操作成功")
          closeDialog()
          refreshData() // 刷新列表
        } catch (error: any) {
          ElMessage.error("视频添加失败")
          console.error("视频添加失败:", error)
        }
      } else {
        console.log("error submit!", fields)
      }
    })
  }

  // 文件选择
  const fileChange = (file: UploadFile, uploadFiles: UploadUserFile[]) => {
    customUpload(file)
    fileList.value = uploadFiles
  }

  // 自定义上传
  const customUpload = async (uploadFile: UploadFile) => {
    const file = uploadFile.raw as File
    if (!file) return

    const fileName = formData.value.videoName || "default"
    const ext = file.name.substring(file.name.lastIndexOf("."))
    const newName = `${fileName}${ext}`

    const formDataParam = new FormData()
    formDataParam.append("file", file, newName)

    try {
      const res = await upload(formDataParam) as { data: { url: string } }
      formData.value.coverUrl = res.data.url
    } catch (error: any) {
      ElMessage.error("上传错误")
      console.error("上传错误:", error)
    }
  }

  return {
    formData,
    formRules,
    formDataRef,
    addDialogVisible,
    isEdit,
    showDialog,
    closeDialog,
    submitForm,
    fileList,
    fileChange
  }
}
